import UIUtil from "../../../GameFramework/Util/UIUtil";
import { EPokerStatus } from "../../ConfigEnum";
import UIPoker from "../../View/UIPoker/UIPoker";
import GameDB, { Poker } from "../GameDB";

const { ccclass, property } = cc._decorator;

@ccclass
export default class GameView extends cc.Component {


    // LIFE-CYCLE CALLBACKS:
    @property(cc.Node) initPokerArea: cc.Node = null
    @property(cc.Prefab) pokerPrefab: cc.Prefab = null
    @property(cc.Node) closeSendArea: cc.Node = null
    @property(cc.Node) openSendArea: cc.Node = null
    @property([cc.Node]) receiveAreaList: cc.Node[] = []
    @property(cc.Node) playGroupRoot: cc.Node = null

    start() {
    }

    public onLoad() {
    }

    public InitPokers(pokers: Poker[]) {
        pokers.forEach((poker, index) => {
            let uiPoker = this.CreateUIPoker(poker)
            uiPoker.node.x = 0.2 * index
            uiPoker.node.y = 0.2 * index
            this.initPokerArea.addChild(uiPoker.node)
        });
    }

    private CreateUIPoker(poker: Poker): UIPoker {
        let uiPokerNode = cc.instantiate(this.pokerPrefab)
        let uiPoker: UIPoker = uiPokerNode.getComponent(UIPoker)
        uiPoker.Init(poker)
        return uiPoker
    }

    private OnPlay() {
        let stack: cc.Node[] = []
        for (let i = this.initPokerArea.children.length - 1; i >= 0; --i) {
            let child = this.initPokerArea.children[i]
            stack.push(child)
            this.initPokerArea.removeChild(child)
        }
        for (let i = stack.length - 1; i >= 0; --i) {
            let child = stack[i]
            this.closeSendArea.addChild(child)
        }

    }

    public OnEventInit(pokers) {
        this.InitPokers(pokers)
    }

    public OnEventPlay() {
        this.OnPlay()
    }

    public OnEventInitGroupCard(groupIndex: number, cardIndex: number, poker: Poker) {
        let index = GameDB.CONST_PLAY_GROUPS*cardIndex - cardIndex*(cardIndex-1)/2 - cardIndex + groupIndex
        let node = poker.view.node
        UIUtil.move(node,this.playGroupRoot)
        node.zIndex = index

        let px = groupIndex * 84
        let delay = 0.3 * index
        if (poker.status == EPokerStatus.OPEN) {
            cc.tween(node)
                .delay(delay)
                .to(0.3, { position: cc.v3(px, cardIndex*-30, 0,) })
                .to(0.2, { scaleX: 0, scaleY: 1 })
                .to(0.2, { scale: 1 })
                .call(()=>{
                    poker.view.Refresh()
                })
                .start()

        } else {
            cc.tween(node)
                .delay(delay)
                .to(0.3, { position: cc.v3(px, cardIndex*-30, 0,) })
                .start()
        }

    }
    // update (dt) {}
}
